#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<signal.h>
#include<errno.h>
#define MAX_BUF_SIZE 100
#define SERVER_PORT 8080
#define BACKLOG 5
int read_all(int fd, void *buf, int n)
{
	int nleft;
	int nbytes;
	char *ptr;
	ptr=buf;
	nleft=n;
	nbytes=read(fd,ptr,nleft);
	ptr[nbytes]='\0';
	if(nbytes<0){
		if(errno=EINTR) nbytes=0;
		else return(-1);
	}
	return(nbytes);
}

void serv_respon(int sockfd){
	int nbytes;
	char buf[MAX_BUF_SIZE];
	while(1){
		nbytes=read_all(sockfd,buf,MAX_BUF_SIZE);
		printf("%s\n",buf);
		if(nbytes==0) return;
		else if(nbytes<0){
			fprintf(stderr,"read error:%s\n",strerror(errno));
			return;
		}
	}
}

int main()
{
	int listenfd,connfd;
	struct sockaddr_in servaddr;
	listenfd=socket(AF_INET,SOCK_STREAM,0);
	if(listenfd<0){
		fprintf(stderr,"socket error\n");
		exit(1);
	}
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
        servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
        servaddr.sin_port=htons(SERVER_PORT);
	if(bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0){
		fprintf(stderr,"bind error\n");
		exit(1);
	}
	if(listen(listenfd,BACKLOG)<0){
		fprintf(stderr,"listen error\n");
		exit(1);
	}
	while(1){
		connfd=accept(listenfd,NULL,NULL);
		if(connfd<0){
			fprintf(stderr,"accept error\n");
			exit(1);
		}
		serv_respon(connfd);
		close(connfd);
	}
	close(listenfd);
}

